package com.stud.system.controller.workflow;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.stud.common.annotation.Log;
import com.stud.common.core.controller.BaseController;
import com.stud.common.core.domain.Result;
import com.stud.common.core.page.TableDataInfo;
import com.stud.common.enums.BusinessType;
import com.stud.common.utils.StringUtils;
import com.stud.common.utils.poi.ExcelUtil;
import com.stud.system.domain.Workflow;
import com.stud.system.dto.WorkflowAuthDTO;
import com.stud.system.request.workflow.WorkflowApproveRequest;
import com.stud.system.request.workflow.WorkflowAuthRequest;
import com.stud.system.request.workflow.WorkflowRejectRequest;
import com.stud.system.request.workflow.WorkflowStartRequest;
import com.stud.system.service.SysRoleService;
import com.stud.system.service.WorkflowService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 流程实例Controller
 *
 * @author Stud
 * @date 2023-03-06
 */
@Api(tags = "流程实例(流程引擎)")
@RestController
@RequestMapping("/system/workflow")
@RequiredArgsConstructor
public class WorkflowController extends BaseController {

    private final WorkflowService workflowService;

    private final SysRoleService roleService;

    @ApiOperation("查询流程实例列表")
    @PreAuthorize("@ss.hasPermi('system:workflow:list')")
    @GetMapping("/list")
    public TableDataInfo<Workflow> list(Workflow workflow) {
        startPage();
        Wrapper<Workflow> wrapper = new QueryWrapper<>(workflow);
        List<Workflow> list = workflowService.list(wrapper);

        if (!CollectionUtils.isEmpty(list)) {
            List<String> roleCodeList = list.stream().map(Workflow::getRoleCode).filter(roleCode -> !StringUtils.isBlank(roleCode)).collect(Collectors.toList());
            Map<String, String> roleKey2Name = roleService.roleKey2Name(roleCodeList.toArray());
            list.forEach(temp -> {
                temp.setRoleName(roleKey2Name.get(temp.getRoleCode()));
            });
        }

        return getDataTable(list);
    }

    @ApiOperation("导出流程实例列表")
    @PreAuthorize("@ss.hasPermi('system:workflow:export')")
    @Log(title = "流程实例", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Workflow workflow) {
        Wrapper<Workflow> wrapper = new QueryWrapper(workflow);
        List<Workflow> list = workflowService.list(wrapper);
        ExcelUtil<Workflow> util = new ExcelUtil<Workflow>(Workflow.class);
        util.exportExcel(response, list, "流程实例数据");
    }

    @ApiOperation("获取流程实例详细信息")
    @GetMapping(value = "/{id}")
    public Result<Workflow> getInfo(@PathVariable("id") Long id) {
        return Result.ok(workflowService.getById(id));
    }

    @ApiOperation("删除流程实例")
    @PreAuthorize("@ss.hasPermi('system:workflow:remove')")
    @Log(title = "流程实例", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public Result<Boolean> remove(@PathVariable Long[] ids) {
        return Result.ok(workflowService.removeByIds(ids));
    }

    @ApiOperation("查询流程相关操作权限")
    @PostMapping("workflowAuth")
    public Result<WorkflowAuthDTO> workflowAuth(WorkflowAuthRequest request) {
        return Result.ok(workflowService.workflowAuth(request));
    }

    @ApiOperation("流程启动")
    @PostMapping("start")
    public Result<Long> start(@Validated WorkflowStartRequest request) {
        return Result.ok(workflowService.start(request.getBusinessId(), request.getBusinessCode()));
    }

    @ApiOperation("流程审批-通过")
    @PostMapping("approve")
    public Result<Long> approve(@Validated WorkflowApproveRequest request) {
        return Result.ok(workflowService.approve(request));
    }

    @ApiOperation("流程审批-驳回")
    @PostMapping("reject")
    public Result<Long> reject(@Validated WorkflowRejectRequest request) {
        return Result.ok(workflowService.reject(request));
    }

    @ApiOperation("流程重置(恢复到流程启动状态)")
    @PostMapping("reset")
    public Result<Long> reset(@RequestParam Long workflowId) {
        return Result.ok(workflowService.reset(workflowId));
    }

}
